package com.system.travel.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.travel.common.exception.BusinessException;
import com.system.travel.common.exception.ErrorCode;
import com.system.travel.modules.system.entity.SysRole;
import com.system.travel.modules.system.mapper.SysRoleMapper;
import com.system.travel.modules.system.service.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统角色Service实现类
 *
 * @author lucas
 * @date 2024/01/01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysRoleMapper roleMapper;

    @Override
    public List<SysRole> getRolesByUserId(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    public SysRole getRoleByCode(String roleCode) {
        return roleMapper.selectByRoleCode(roleCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long roleId, Integer status) {
        // 获取角色信息
        SysRole role = getById(roleId);
        if (role == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND);
        }

        // 更新状态
        role.setStatus(status);
        updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignPermissions(Long roleId, List<Long> permissionIds) {
        // 获取角色信息
        SysRole role = getById(roleId);
        if (role == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND);
        }

        // 删除原有权限
        roleMapper.deleteRolePermissions(roleId);

        // 分配新权限
        if (permissionIds != null && !permissionIds.isEmpty()) {
            roleMapper.insertRolePermissions(roleId, permissionIds);
        }
    }

    @Override
    public List<Long> getPermissionIds(Long roleId) {
        return roleMapper.selectPermissionIds(roleId);
    }
} 